package week3rd;

public class CircularArrayQueue<T> implements QueueADT<T>
{
    private final static int DEFAULT_CAPACITY = 100;
    private int front, rear, count;
    private T[] queue; 
  

    public CircularArrayQueue (int initialCapacity)
    {
        front = rear = count = 0;
        queue = (T[]) (new Object[initialCapacity]);
    }
  

    public CircularArrayQueue()
    {
        this(DEFAULT_CAPACITY);
    }    
	

    public void enqueue(T element)
    {
        if (size() == queue.length) 
            expandCapacity();
    
        queue[rear] = element;
        rear = (rear+1) % queue.length;
    
        count++;
    }
	

    private void expandCapacity()
    {
        T[] larger = (T[]) (new Object[queue.length *2]);
    
        for (int scan = 0; scan < count; scan++)
        {
            larger[scan] = queue[front];
            front = (front + 1) % queue.length;
        }
    
        front = 0;
        rear = count;
        queue = larger;
    }
	

    public T dequeue() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("queue");
    
        T result = queue[front];
        queue[front] = null;
        front = (front+1) % queue.length;
    
        count--;
    
        return result;
    }
  

    public T first() throws EmptyCollectionException
    {
        if (isEmpty()) {
            throw new EmptyCollectionException("empty");
        }
        T result = queue[front];

        return  result;
    }
  
    /**
     * Returns true if this queue is empty and false otherwise.
     * @return true if this queue is empty 
     */
    public boolean isEmpty()
    {
        boolean b ;
        if (size() == 0)
            b = true;
        else
            b = false;
        return b;
    }
  
    /**
     * Returns the number of elements currently in this queue.
     * @return the size of the queue
     */
    public int size()
    {
        return count;
    }
  
    /**
     * Returns a string representation of this queue. 
     * @return the string representation of the queue
     */
    public String toString()
    {
        String str = "[";
        if (front == rear)
            str = "[  ";
        else if (front < rear)
            for (int i = front; i < rear; i++)
            {
                str += queue[i] + ", ";
            }
        else if (front > rear) {
            for (int i = front; i < DEFAULT_CAPACITY; i++) {
                str += queue[i] + ", ";
            }
            for (int i = 0; i < rear; i++) {
                str += queue[i] + ", ";
            }
        }

        str = str.substring(0,str.length()-2);



        str += "]";

        return str;
    }
}
